<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书列表展示</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/list.css">
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script src="js/jq-paginator.js"></script>
</head>
<body>
<div class="bookContainer">
    <h2>图书列表展示</h2>
    <div class="navbar-justify-between">
        <div>
            <button class="btn btn-outline-info" type="button" onclick="location.href='book_add.html'">添加图书</button>
            <button class="btn btn-outline-info" type="button" onclick="batchDelete()">批量删除</button>
        </div>
    </div>

    <table>
        <thead>
        <tr>
            <td>选择</td>
            <td class="width100">图书ID</td>
            <td>书名</td>
            <td>作者</td>
            <td>数量</td>
            <td>定价</td>
            <td>出版社</td>
            <td>状态</td>
            <td class="width200">操作</td>
        </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div class="demo">
        <ul id="pageContainer" class="pagination justify-content-center"></ul>
    </div>
    <script>
        // 初始化分页组件
        function initPagination(totalCounts, currentPage) {
            $("#pageContainer").jqPaginator({
                totalCounts: totalCounts, // 总记录数
                pageSize: 10, // 每页大小
                visiblePages: 5, // 可见的分页按钮数量
                currentPage: currentPage, // 当前页码
                first: '<li class="page-item"><a class="page-link">首页</a></li>',
                prev: '<li class="page-item"><a class="page-link">上一页</a></li>',
                next: '<li class="page-item"><a class="page-link">下一页</a></li>',
                last: '<li class="page-item"><a class="page-link">最后一页</a></li>',
                page: '<li class="page-item"><a class="page-link">{{page}}</a></li>',
                onPageChange: function (page, type) {
                    console.log("第" + page + "页，类型：" + type);

                    // 更新URL中的pageNum参数（不刷新页面）
                    const newUrl = new URL(window.location.href);
                    newUrl.searchParams.set('pageNum', page);
                    window.history.pushState({}, '', newUrl.toString());

                    // 重新加载数据
                    getBookList(page);
                }
            });
        }

        // 加载图书列表
        function getBookList(pageNum) {
            console.log("加载第" + pageNum + "页数据");

            const params = new URLSearchParams();
            params.append('pageNum', pageNum);
            params.append('pageSize', 10);

            $.ajax({
                url: "/book/getBookListByPage?" + params.toString(),
                type: "get",
                success: function (response) {
                    // 用户未登录
                    if (response.code == "NOLIGIN") {
                        location.href = "login.html";
                        return;
                    }

                    // 打印调试信息
                    console.log("响应数据：", response);
                    if (response.data) {
                        console.log("records 数据：", response.data.records);
                    }

                    // 检查数据是否为空
                    if (!response.data || !response.data.records || response.data.records.length === 0) {
                        $("tbody").html('<tr><td colspan="9" class="text-center">没有图书</td></tr>');
                        return;
                    }

                    // 渲染表格
                    const books = response.data.records;
                    const finalHtml = [];
                    books.forEach(book => {
                        finalHtml.push(`
                    <tr>
                        <td><input type="checkbox" name="selectBook" value="${book.id}" class="book-select"></td>
                        <td>${book.id}</td>
                        <td>${book.bookName}</td>
                        <td>${book.author}</td>
                        <td>${book.count}</td>
                        <td>${book.price}</td>
                        <td>${book.publish}</td>
                        <td>${book.statusCN}</td>
                        <td>
                            <div class="op">
                                <a href="book_update.html?bookId=${book.id}">修改</a>
                                <a href="javascript:void(0)" onclick="deleteBook(${book.id})">删除</a>
                            </div>
                        </td>
                    </tr>
                `);
                    });
                    $("tbody").html(finalHtml.join(''));

                    // 初始化分页组件
                    if (!window.paginationInitialized && response.data && response.data.count) {
                        initPagination(response.data.count, parseInt(pageNum));
                        window.paginationInitialized = true;
                    }
                },
                error: function (error) {
                    console.log(error);
                    if(error != null && error.status == 401){
                        location.href = "login.html";
                    }
                },

            });
        }





        function deleteBook(id) {
            var isDelete = confirm("确认删除？");
            if(isDelete){
                //删除图书：
                $.ajax({
                    url: "/book/deleteBook",
                    type: "post",
                    data:{
                        bookId: id
                    },
                    success:function (result){
                        if(result == ""){
                            location.href = "book_list.html";
                        }else{
                            alert(result);
                        }
                    }
                });
            }
        }

        function batchDelete() {
            var isDelelte  = confirm("确认批量删除？");
            if(isDelelte){
                //获取复选框中的id：
                var ids = [];
                $("input:checkbox[name='selectBook']:checked").each(function (){
                    ids.push($(this).val());

                });
                console.log(ids);
                $.ajax({
                    url: "/book/batchDeleteBook?ids="+ids,
                    type: "post",
                    success: function (result){
                        if(result == ""){
                            //删除成功了，就刷新这个页面：
                            location.href = "book_list.html";
                        }else{
                            //弹出错误信息：
                            alert(result);
                        }
                    }
                })
            }
        }

        $(document).ready(function () {
            // 初始化加载第一页数据
            const urlParams = new URLSearchParams(window.location.search);
            const pageNum = urlParams.get('pageNum') || 1; // 从URL中读取pageNum，默认1
            getBookList(pageNum);
        });
    </script>
</div>
</body>
</html>
